package handlers

import (
	"encoding/json"
	"github.com/gin-gonic/gin"
	"news-hub/cache"
	"news-hub/model"
	"news-hub/pkg"
	"time"
)

func Login(c *gin.Context) {
	username := c.PostForm("username")
	password := c.PostForm("password")
	if username == "" || password == "" {
		c.JSON(200, gin.H{
			"code": 400,
			"msg":  "字段不能为空",
		})
		return
	}
	resdis_key := "redis_login_" + username
	errCount, _ := cache.Rdb.Get(cache.Ctx, resdis_key).Int()
	if errCount >= 3 {
		c.JSON(200, gin.H{
			"code": 400,
			"msg":  "密码错误超过3次，禁止登录",
		})
		return
	}
	var user model.User
	err := model.DB.Where("username = ?", username).Find(&user).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 400,
			"msg":  "查询用户失败",
		})
		return
	}
	if user.ID == 0 {
		c.JSON(200, gin.H{
			"code": 400,
			"msg":  "用户不存在",
		})
		return
	}
	if user.Password != pkg.Str(password) {
		cache.Rdb.Incr(cache.Ctx, resdis_key)
		if errCount == 2 {
			cache.Rdb.Set(cache.Ctx, resdis_key, 3, time.Hour*2)
			c.JSON(200, gin.H{
				"code": 400,
				"msg":  "密码错误3次，封禁2小时",
			})
			return
		}
		c.JSON(200, gin.H{
			"code": 400,
			"msg":  "密码不正确",
		})
		return
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "登录成功",
	})
	return
}

func Collect(c *gin.Context) {
	var news []model.News
	redis_key := "redis_list_"
	cacheData, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	if cacheData == "" {
		model.DB.Find(&news)
		jsonData, _ := json.Marshal(news)
		cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*3)
	} else {
		json.Unmarshal([]byte(cacheData), &news)
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "查询成功",
		"data": news,
	})
	return
}

func Detail(c *gin.Context) {
	id := c.Query("id")
	var news model.News
	redis_key := "redis_del_" + id
	cacheData, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	if cacheData == "" {
		model.DB.Where("id = ?", id).Find(&news)
		jsonData, _ := json.Marshal(news)
		cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*3)
	} else {
		json.Unmarshal([]byte(cacheData), &news)
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "查询成功",
		"data": news,
	})
	return
}
